package top.yonyong.mock.service.impl;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.yonyong.mock.entity.Student;
import top.yonyong.mock.mapper.StudentMapper;
import top.yonyong.mock.service.UserService;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author yonyong
 **/
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService{

    @Resource
    private StudentMapper studentMapper;

    @Override
    @Transactional(readOnly = true)
    public List<Student> getAll() {
        return studentMapper.selectAll();
    }

    @Override
    public boolean delete(Student student) {
        if (ObjectUtil.isNull(student)){
            log.error("student is null");
            return false;
        }

        final int i = studentMapper.selectCount(student);
        if (i == 0){
            log.error("query result is null");
            return false;
        }

        final int delete = studentMapper.delete(student);
        if (delete <= 0){
            log.error("delete fail,affect rows: " + delete);
            return false;
        }else {
            log.info("delete ok");
            return true;
        }
    }

    @Override
    public boolean update(Student student) {
        if (ObjectUtil.isNull(student)){
            log.error("student is null");
            return false;
        }

        final int i = studentMapper.selectCount(student);
        if (i == 0){
            log.error("query result is null");
            return false;
        }

        final int affectRows = studentMapper.updateByPrimaryKeySelective(student);
        if (affectRows <= 0){
            log.error("update fail,affect rows: " + affectRows);
            return false;
        }else {
            log.info("update ok");
            return true;
        }
    }

    @Override
    public boolean insert(Student student) {
        if (ObjectUtil.isNull(student)){
            log.error("student is null");
            return false;
        }

        final int i = studentMapper.selectCount(student);
        if (i > 0){
            log.error("the student has existed in db");
            return false;
        }

        final int affectRows = studentMapper.insert(student);
        if (affectRows <= 0){
            log.error("insert fail,affect rows: " + affectRows);
            return false;
        }else {
            log.info("insert ok");
            return true;
        }
    }
}
